//
//  AppDelegate.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/10/30.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "AppDelegate.h"

//controllers
#import "Home_Root_Controller.h"
#import "Service_Root_Controller.h"
#import "ShoppingCart_Root_Controller.h"
#import "Strore_Root_Controller.h"
#import "IntroductionController.h"
#import "BaiDuLocationViewController.h"
#import "UserCenter_Controller.h"
#import "LoadPageLocationController.h"
//vendor
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "MTA.h"
#import "MTAConfig.h"
#import "NSString+Conversion.h"
//baidu
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
//model
#import "XiaoQuAndStoreInfoModel.h"
//untils
#import "Global.h"
#import "UIColor+Hex.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
#import "FMDBManager.h"
#import "RealReachability.h"
//zhifubao
#import <AlipaySDK/AlipaySDK.h>
@interface AppDelegate ()<BMKGeneralDelegate>
{
     RDVTabBarController *_rootViewController;
    
    UINavigationController *navigationController;
    BMKMapManager* _mapManager;
}
@property (nonatomic,strong) NSString *updataFlag;//升级类型
@property (nonatomic,strong) NSString *updataURL;//升级地址
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //设置navBar
    [self setNavBarStyleWith:application];
    [self setConfigureInfoWithOptions:launchOptions];
    //创建数据库
    [self setUpSqlite];
    [self startNetworkReachability];
    //立即体验
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endIntroductionPage) name:End_IntroductionPage object:nil];
    //定位成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dingWeiSuccess) name:DINGWEISUCCESS object:nil];
    //定位失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dingWeiFailed) name:DINGWEIFAILED object:nil];
    //商品种类个数改变时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productCountChange) name:PRODUCTCOUNTCHANGE object:nil];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:Phone_Signature] length] != 0) {//如果有手机签名证明不是第一次进入
        //因为每次启动应用（除第一次安装）都需要定位，进入加载页（类似加载页）中定位
        [self checkUpdate];//检测更新
        //有账号自动登录
        UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
        if (model.userPassword.length != 0) {
            [ManagerGlobeUntil sharedManager].transactionLogin = YES;
        }
        LoadPageLocationController *loadPageLocationVC = [[LoadPageLocationController alloc]init];
        self.window.rootViewController = loadPageLocationVC;
        [self.window makeKeyAndVisible];
        
    } else {//如果没有手机签名证明是第一次进入
        IntroductionController *registerVC = [[IntroductionController alloc]init];
        self.window.rootViewController = registerVC;
        [self.window makeKeyAndVisible];
    }
    
    
    return YES;
    
}
#pragma mark - 创建数据库和历史表 和购物车表
-(void)setUpSqlite
{
    //创建数据库文件
    [[FMDBManager sharedManager]initWithCreateSqlite];
    //创建历史表
    [[FMDBManager sharedManager]initWithHistoryCreateTable];
    //创建购物车表
    [[FMDBManager sharedManager]initWithShoppingCartTable];
  
    
}
#pragma mark --支付宝
-(void)zhifubaoResult
{
    
}
#pragma mark - 通知事件
//结束引导页，立即体验
- (void)endIntroductionPage {
        BaiDuLocationViewController *dingWeiVC = [[BaiDuLocationViewController alloc]init];
        dingWeiVC.suppperControllerType = kIntroduction_ControllerSupperController;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:dingWeiVC];
        self.window.rootViewController = nav;
        [self.window makeKeyAndVisible];
}
//定位成功
- (void)dingWeiSuccess {
    [self initRootController];//更新显示视图
}
//定位失败
- (void)dingWeiFailed {
    BaiDuLocationViewController *baiDuLocationVC = [[BaiDuLocationViewController alloc]init];
    baiDuLocationVC.suppperControllerType = kIntroduction_ControllerSupperController;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:baiDuLocationVC];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
}
//商品种类个数改变时
- (void)productCountChange {
    RDVTabBarItem *tabBarItem = [_tabBarController.tabBar.items objectAtIndex:3];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableArray *array=[[FMDBManager sharedManager]QueryDataWithshopID:model.storeID];
     NSInteger totalNum = 0;
    for (NSDictionary *dic in array) {
        NSString *buynum =[dic objectForKey:@"buynum"];
        
        totalNum=totalNum+buynum.integerValue;
    }
    tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",(long)totalNum];
    if ([tabBarItem.badgeValue isEqualToString:@"0"]) {
        tabBarItem.badgeValue = nil;
    }
}
#pragma mark -- 检测更新
- (void)checkUpdate {
    /*
     ADAPTER	业务适配器	区分大小写
     TYPE	类别	A.Android B.iPhone C.iPad
     VERSION	版本号	客户端版本号
     SIGNATURE
     */
    
    ManagerHttpBase *manger = [ManagerHttpBase sharedManager];
    
    [manger rigisterTestingUpdate:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         /*
          STATE	状态	0为成功，错误对应相应的错误代码
          MSG	错误信息	登陆失败时返回该消息
          UPDATEFLG	是否需要升级	A不升级B升级C强制升级
          CURVER	最新版本号
          DOWNURL	下载地址
          UPDATELOG	升级内容
          RELEASEDATE	发布日期
          */
         if ([responseObject isKindOfClass:[NSDictionary class]]) {
             NSDictionary *dataDic = (NSDictionary*)[responseObject objectForKey:@"OBJECT"];
             NSString *state = [NSString stringTransformObject:[responseObject objectForKey:@"STATE"]];
             if (state.intValue == 0)
             {
                 //A：没有新版本，不需要升级 B：有新版本，可以升级 C：有新版本，该版本要求强制升级
                 NSString *updateFlag = [NSString stringTransformObject:[dataDic objectForKey:@"UPDATEFLG"]];
                 self.updataFlag = updateFlag;
                 self.updataURL = [NSString stringTransformObject:[dataDic objectForKey:@"DOWNURL"]];
                 
                 NSString *updateLog = [NSString stringWithFormat:@"%@",[NSString stringTransformObject:[dataDic objectForKey:@"UPDATELOG"]]];
                 updateLog = [updateLog stringByReplacingOccurrencesOfString:@"rn" withString:@"\r"];
                 
                 
                 NSString *msg = [NSString stringWithFormat:@"当前版本:%@\r最新版本:%@\r发布日期:%@\r %@"
                                  ,[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
                                  ,[NSString stringTransformObject:[dataDic objectForKey:@"CURVER"]]
                                    ,[NSString stringTransformObject:[dataDic objectForKey:@"RELEASEDATE"]]
                                  ,updateLog];
                 
                 
                 //更新提示，当前版本，最新版本，发布日期
                 if ([updateFlag isEqualToString:@"C"]){//强制升级
                     UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"更新提示"
                                                                        message:msg
                                                                       delegate:self
                                                              cancelButtonTitle:@"升级"
                                                              otherButtonTitles:nil];
                     alertView.tag = COMPEL_UPDATA_TAG;
                     [alertView show];
                 }else if ([updateFlag isEqualToString:@"B"]){//不强制升级
                     UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"更新提示"
                                                                        message:msg
                                                                       delegate:self
                                                              cancelButtonTitle:@"取消"
                                                              otherButtonTitles:@"升级",nil];
                     alertView.tag = UPDATA_TAG;
                     [alertView show];
                 }
             } else {//请求失败
                 
             }
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         
         
     }];
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger tag = alertView.tag;
    switch (tag) {
        case COMPEL_UPDATA_TAG://强制更新
        {
            NSURL *url = [NSURL URLWithString:self.updataURL];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
            
            break;
        }
        case UPDATA_TAG://普通更新
        {
            switch (buttonIndex) {
                case 0:
                    
                    break;
                case 1:
                {
                    NSURL *url = [NSURL URLWithString:self.updataURL];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                }
                    break;
                    
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
}

#pragma mark -- 配置信息
- (void)setConfigureInfoWithOptions:(NSDictionary*)launchOptions {
    //腾讯云分析
    [self setMTA];
    //分享平台配置
    [self setSharePlat];
    [self setBaiDuKey];
}

//腾讯云分析测试 --I389CYWM5IVC
//腾讯云分析正式 --I44M8XAUIG4G
- (void)setMTA {
//     [MTA startWithAppkey:@"I44M8XAUIG4G"];
    [MTA startWithAppkey:@"I389CYWM5IVC"];
    [MTA startNewSession];
}
//百度地图测试key   --IpRaoBQ3d6aYV6eXDYbMBCqp
//百度地图正式key   --rDC2O1fDOBZkDGbG2Lm0UlKM
- (void)setBaiDuKey {
    //baiduditu
    _mapManager = [[BMKMapManager alloc]init];
     BOOL ret = [_mapManager start:@"rDC2O1fDOBZkDGbG2Lm0UlKM"  generalDelegate:self];
//     BOOL ret = [_mapManager start:@"IpRaoBQ3d6aYV6eXDYbMBCqp"  generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
}
// 分享平台正式-- AppID：wxb595a449fa9ba651
- (void)setSharePlat {
    //TODO:ShareSDK 分享
    /**
     注册SDK应用，此应用请到http://www.sharesdk.cn中进行注册申请。
     此方法必须在启动时调用，否则会限制SDK的使用。
     **/
    [WXApi registerApp:@"wxb595a449fa9ba651"];
     
}

//开启网络监听
- (void)startNetworkReachability {
//    [GLobalRealReachability startNotifier];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(networkChanged:)
//                                                 name:kRealReachabilityChangedNotification
//                                               object:nil];
     [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
            {
                NSLog(@"无网络");
                [ManagerGlobeUntil sharedManager].isNetworkReachability = NO;
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"WiFi网络");
                [ManagerGlobeUntil sharedManager].isNetworkReachability = YES;
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"无线网络");
                [ManagerGlobeUntil sharedManager].isNetworkReachability = YES;
                break;
            }
                
            default:
                break;
        }
    }];
}
- (void)stopNetworkReachability {
//    [GLobalRealReachability stopNotifier];
}
- (void)networkChanged:(NSNotification *)notification
{
//    RealReachability *reachability = (RealReachability *)notification.object;
//    ReachabilityStatus status = [reachability currentReachabilityStatus];
//    NSLog(@"currentStatus:%@",@(status));
//    
//    if (status == NotReachable)
//    {
//        NSLog(@"未连接到网络");
//        [ManagerGlobeUntil sharedManager].isNetworkReachability = NO;
//    }
//    
//    if (status == ReachableViaWiFi || status == ReachableViaWWAN)
//    {
//       NSLog(@"已连接到网络");
//       [ManagerGlobeUntil sharedManager].isNetworkReachability = YES;
//    }
    
}

#pragma mark -- 注册成功初始化跟视图
- (void)initRootController {
    [self setupRootController];
    [self setupTabBarStyle];
    [self productCountChange];
    [self.window setRootViewController:_rootViewController];
    [self.window makeKeyAndVisible];
}

#pragma mark -- 设置视图

- (void)setupRootController {
    //首页
    Home_Root_Controller *firstViewController = [[Home_Root_Controller alloc] init];
    UIViewController *firstNavigationController = [[UINavigationController alloc]
                                                   initWithRootViewController:firstViewController];
    //便利店
    Strore_Root_Controller *secondViewController = [[Strore_Root_Controller alloc] init];
    UIViewController *secondNavigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:secondViewController];
    //服务
    Service_Root_Controller *thirdViewController = [[Service_Root_Controller alloc] init];
    UIViewController *thirdNavigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:thirdViewController];
    //购物车
    ShoppingCart_Root_Controller *fourthViewController = [[ShoppingCart_Root_Controller alloc] init];
    UIViewController *fourthNavigationController = [[UINavigationController alloc]
                                                   initWithRootViewController:fourthViewController];
    
    //个人中心
    UserCenter_Controller *fiveViewController = [[UserCenter_Controller alloc] init];
    UIViewController *fiveNavigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:fiveViewController];
    
    _tabBarController = [[RDVTabBarController alloc] init];
    [_tabBarController setViewControllers:@[firstNavigationController, secondNavigationController,
                                            thirdNavigationController,fourthNavigationController,fiveNavigationController]];
    _tabBarController.delegate = (id<RDVTabBarControllerDelegate>)self;
    _rootViewController = _tabBarController;
    
}

#pragma mark -- RDVTabBarControllerDelegate
- (void)tabBarController:(RDVTabBarController *)tabBarController didSelectViewControllerAtIndex:(NSInteger )index {
    
    [self changeTabBarSelectedIndex:index];
    
}
//设置选中下标和先前选中下标
- (void)changeTabBarSelectedIndex:(NSInteger)index{
    self.oldSelectedTabBarIndex = self.currentSelectedTabBarIndex;
    self.currentSelectedTabBarIndex = index;
}
//外部设置tabBar选中下标
- (void)selectedControllerAtTabBarIndex:(NSInteger)index {
    [self changeTabBarSelectedIndex:index];
    _tabBarController.selectedIndex = index;
}

#pragma mark -- 设置tabBar样式
- (void)setupTabBarStyle {
    UIImage *normal_BG_Image = [UIImage imageNamed:@"Tab_normal_bg"];
    //标题属性（字体大小，字体颜色）可以在RDVTabBarItem内部设置也可以在这里设置
    _rootViewController.tabBar.backgroundColor = [UIColor colorWithPatternImage:normal_BG_Image];
    NSArray *titles = @[@"首页", @"便利店", @"服务", @"购物车",@"我的"];
    NSArray *normalImages = @[@"Tab_FirstItem_Normal"
                        ,@"Tab_SecondItem_Normal"
                        ,@"Tab_ThridItem_Normal"
                        ,@"Tab_FourthItem_Normal",@"Tab_FiveItem_Normal"];
    
    NSArray *selectedImages = @[@"Tab_FirstItem_Selected"
                                ,@"Tab_SecondItem_Selected"
                                ,@"Tab_ThridItem_Selected"
                                ,@"Tab_FourthItem_Selected",@"Tab_FiveItem_Selected"];
    
    for (NSInteger i = 0; i < [[[_rootViewController tabBar] items] count]; i++) {
        
        RDVTabBarItem *item = [[[_rootViewController tabBar] items] objectAtIndex:i];
        UIImage *itemNormal_BG_Image = [UIImage imageNamed:[normalImages objectAtIndex:i]];
        UIImage *itemSelected_BG_image = [UIImage imageNamed:[selectedImages objectAtIndex:i]];
        [item setFinishedSelectedImage:itemSelected_BG_image withFinishedUnselectedImage:itemNormal_BG_Image];
        item.title = [titles objectAtIndex:i];
    }
    
}

#pragma mark -- 设置navigation Bar 样式
//设置状态栏和navBarStyle
- (void)setNavBarStyleWith:(UIApplication *)application
{
    //设置NavBar背景
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    
    //修改标题颜色
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor] , NSForegroundColorAttributeName ,
                          [UIFont fontWithName:@"Helvetica-Bold" size:18.0f],NSFontAttributeName,
                          nil];
    [[UINavigationBar appearance] setTitleTextAttributes:dic];
    
    //设置NavBar
    UIImage *image = [UIImage imageNamed:@"Nav_bg_Image"];
   image = [image stretchableImageWithLeftCapWidth:8 topCapHeight:8];
    if (IsIOS7) {
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
        [[UINavigationBar appearance] setBackgroundImage:image
                                          forBarPosition:UIBarPositionTop
                                              barMetrics:UIBarMetricsDefault];
    } else {
        [application setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
        [[UINavigationBar appearance] setBackgroundImage:image
                                           forBarMetrics:UIBarMetricsDefault];
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    [ManagerGlobeUntil sharedManager].appIsWake = NO;
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
   [ManagerGlobeUntil sharedManager].appIsWake = YES;
    if (self.updataFlag && ([self.updataFlag isEqualToString:@"C"]||[self.updataFlag isEqualToString:@"B"])) {
        [self checkUpdate];
        
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
 
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            
        }];
    }else if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】

        }];
    }else{
          [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}


#pragma mark - WXApiDelegate

-(void) onReq:(BaseReq*)req
{
    
}

-(void) onResp:(BaseResp*)resp
{
    NSString *state = [NSString stringWithFormat:@"%d",resp.errCode];
    if ([resp isKindOfClass:[PayResp class]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:WEIXINPAYRESULT object:nil userInfo:@{@"state":state}];
    }
}


#pragma mark -- BMKGeneralDelegate（网络连接判断和授权状态）
- (void)onGetNetworkState:(int)iError
{
    if (iError) {
        NSLog(@"%d", iError);
    } else {
        NSLog(@"百度地图网络连接成功");
    }
}

- (void)onGetPermissionState:(int)iError
{
    if (iError) {
        
        
    } else {
        
    }
}

@end
